<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;
use think\Log;
use think\Db;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','wx_login'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="account", type="string", required=true, description="账号")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        // $captcha = $this->request->post('captcha');
        // if (!$mobile || !$captcha) {
        //     $this->error(__('Invalid parameters'));
        // }
        // if (!Validate::regex($mobile, "^1\d{10}$")) {
        //     $this->error(__('Mobile is incorrect'));
        // }
        // if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
        //     $this->error(__('Captcha is incorrect'));
        // }
        
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="code", type="string", required=true, description="验证码")
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }
    /**
     * 微信授权获取openid
     *
     * @return void
     */
    public function wx_login()
    {
        // 参数验证
        $param = $this->request->param();
        if (empty($param['js_code'])) {
            $this->error(__('Invalid parameters'));
        }
    
        // 获取微信配置
        $config = \app\common\model\Config::get(['name' => '小程序']);
        if (!$config) {
            Log::error('微信登录配置缺失');
            $this->error(__('Configuration error'));
        }
    
        $wx_config = json_decode($config['value'], true);
        $appid     = $wx_config['appid'] ?? '';
        $secret    = $wx_config['secret'] ?? '';
    
        if (empty($appid) || empty($secret)) {
            Log::error('微信登录配置错误: appid 或 secret 为空');
            $this->error(__('Configuration error'));
        }
    
        try {
            $get = [
                'appid'      => $appid,
                'secret'     => $secret,
                'js_code'    => $param['js_code'],
                'grant_type' => 'authorization_code'
            ];
    
            // 发起请求并验证响应
            $result = curlGet('https://api.weixin.qq.com/sns/jscode2session', $get);
            $result = json_decode($result, true);
    
            if (isset($result['errcode']) && $result['errcode'] != 0) {
                Log::error('微信登录接口错误: ' . $result['errmsg']);
                $this->error(__('WeChat API error: ') . $result['errmsg']);
            }
    
            if (!isset($result['openid'])) {
                Log::error('微信登录返回数据异常: 缺少 openid');
                $this->error(__('Invalid response from WeChat'));
            }
    
            $openid  = $result['openid'];
            $unionid = $result['unionid'] ?? '';
    
            // 查询用户
            $user = \app\common\model\User::getByOpenid($openid);
    
            if ($user) {
                if ($user->status != 'normal') {
                    $this->error(__('Account is locked'));
                }
                $ret = $this->auth->direct($user->id);
            } else {
                $user = \app\common\model\User::create([
                    'unionid'  => $unionid,
                    'openid'   => $openid,
                    'status'   => 'normal',
                    'share_id' => $param['from_id'] ?? ''
                ]);
                $ret = $this->auth->direct($user->id);
            }
    
            if ($ret) {
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success(__('Logged in successful'), $data);
            } else {
                $this->error($this->auth->getError());
            }
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            Log::error('微信登录请求失败: ' . $e->getMessage());
            $this->error(__('Network request failed'));
        }
    }
    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }
    public function getuserphonenumber(){
        $data = request()->param();
        if(empty($data['code']) || empty($data['openid']))return $this->error('参数错误');
        $config    = \app\common\model\Config::get(['name'=>'小程序']);
        //Log::info($config);
        $wx_config = json_decode($config['value'],true);
        // 验证配置项
        //Log::info($wx_config);
        $appid  = $wx_config['appid']??'wx3f4d29ad53d2bfa9';
        $secret = $wx_config['secret']??'474cf38f8c2d250330bf47b18cf0f336';
        if (empty($appid) || empty($secret)) {
            Log::error('微信登录配置错误: appid 或 secret 为空');
            $this->error(__('Configuration error'));
        }
        $result = \WeChat::get_phoneNum($appid,$secret,$data);
        if($result['errcode'] === 0){
            $user     = $this->auth->getUser();
            $user->mobile= $result['phone_info']['purePhoneNumber'];
            $user->save();
            $this->success('获取成功', $result['phone_info']);
        }
        return $this->error($result['errmsg']);
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="platform", type="string", required=true, description="平台名称")
     * @ApiParams (name="code", type="string", required=true, description="Code码")
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="newpassword", type="string", required=true, description="新密码")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
}
